import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { appConfig } from '@/config'
import { logger } from '@/utils/logger'

export const useAppStore = defineStore('app', () => {
  // 状态
  const isLoading = ref(false)
  const error = ref(null)
  const fontSize = ref(appConfig.fontSize.default)
  const sidebarCollapsed = ref(false)
  const notifications = ref([])
  
  // 计算属性
  const fontSizeOptions = computed(() => appConfig.fontSize.options)
  
  const currentFontSizeOption = computed(() => {
    return fontSizeOptions.value.find(option => option.value === fontSize.value) || 
           fontSizeOptions.value[1] // 默认中等字体
  })
  
  const fontSizeClass = computed(() => currentFontSizeOption.value.class)
  
  
  const hasError = computed(() => !!error.value)
  
  const hasNotifications = computed(() => notifications.value.length > 0)
  
  // 方法
  function setLoading(loading) {
    isLoading.value = loading
    logger.debug('设置加载状态:', loading)
  }
  
  function setError(errorMessage) {
    error.value = errorMessage
    if (errorMessage) {
      logger.error('应用错误:', errorMessage)
    }
  }
  
  function clearError() {
    error.value = null
    logger.debug('清除错误信息')
  }
  
  function setFontSize(size) {
    const validOption = fontSizeOptions.value.find(option => option.value === size)
    if (validOption) {
      fontSize.value = size
      localStorage.setItem(appConfig.storageKeys.fontSize, size)
      document.documentElement.classList.remove(...fontSizeOptions.value.map(o => o.class))
      document.documentElement.classList.add(validOption.class)
      logger.userAction('修改字体大小', { fontSize: size })
    }
  }
  
  function increaseFontSize() {
    const currentIndex = fontSizeOptions.value.findIndex(option => option.value === fontSize.value)
    if (currentIndex < fontSizeOptions.value.length - 1) {
      setFontSize(fontSizeOptions.value[currentIndex + 1].value)
    }
  }
  
  function decreaseFontSize() {
    const currentIndex = fontSizeOptions.value.findIndex(option => option.value === fontSize.value)
    if (currentIndex > 0) {
      setFontSize(fontSizeOptions.value[currentIndex - 1].value)
    }
  }
  
  
  function toggleSidebar() {
    sidebarCollapsed.value = !sidebarCollapsed.value
    logger.userAction('切换侧边栏', { collapsed: sidebarCollapsed.value })
  }
  
  function addNotification(notification) {
    const id = Date.now().toString()
    const newNotification = {
      id,
      type: 'info',
      duration: 5000,
      ...notification,
      timestamp: new Date().toISOString()
    }
    
    notifications.value.push(newNotification)
    
    if (newNotification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, newNotification.duration)
    }
    
    logger.info('添加通知:', newNotification)
    return id
  }
  
  function removeNotification(id) {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
  }
  
  function clearNotifications() {
    notifications.value = []
  }
  
  function reset() {
    isLoading.value = false;
    error.value = null;
    notifications.value = [];
    // 重置字体大小到初始值
    localStorage.removeItem(appConfig.storageKeys.settings);
    localStorage.removeItem(appConfig.storageKeys.fontSize);
    // 移除所有字体大小类
    document.documentElement.classList.remove(...fontSizeOptions.value.map(o => o.class));
    initializeSettings(); // 重新初始化设置
  }

  function getSettings() {
    try {
      const settings = localStorage.getItem(appConfig.storageKeys.settings)
      return settings ? JSON.parse(settings) : {}
    } catch {
      return {}
    }
  }
  
  function initializeSettings() {
    // 初始化字体大小
    const savedFontSize = localStorage.getItem(appConfig.storageKeys.fontSize)
    if (savedFontSize && fontSizeOptions.value.find(option => option.value === savedFontSize)) {
      fontSize.value = savedFontSize
    }
    
    // 确保在初始化时应用正确的字体大小类
    const currentFontClass = fontSizeOptions.value.find(option => option.value === fontSize.value)?.class || fontSizeOptions.value[1].class;
    document.documentElement.classList.add(currentFontClass);

    // 初始化其他设置
    const settings = getSettings()
    if (settings.sidebarCollapsed !== undefined) {
      sidebarCollapsed.value = settings.sidebarCollapsed
    }
    
    logger.info('应用设置初始化完成', {
      fontSize: fontSize.value,
      sidebarCollapsed: sidebarCollapsed.value
    })
  }
  
  return {
    // 状态
    isLoading,
    error,
    fontSize,
    sidebarCollapsed,
    notifications,
    
    // 计算属性
    fontSizeOptions,
    currentFontSizeOption,
    fontSizeClass,
    hasError,
    hasNotifications,
    
    // 方法
    setLoading,
    setError,
    clearError,
    setFontSize,
    increaseFontSize,
    decreaseFontSize,
    toggleSidebar,
    addNotification,
    removeNotification,
    clearNotifications,
    reset,
    getSettings,
    initializeSettings,
  }
})

// 在useAppStore外部定义，避免循环依赖问题
export const resetAllStores = () => {
  console.log('🔄 正在重置所有Pinia store...');
  useAppStore().reset();
  
  // 使用动态导入避免循环依赖
  import('./favorites').then(({ useFavoritesStore }) => useFavoritesStore().reset()).catch(() => {});
  import('./articleDetail').then(({ useArticleDetailStore }) => useArticleDetailStore().reset()).catch(() => {});
  import('./article').then(({ useArticleStore }) => useArticleStore().reset()).catch(() => {});
  import('./browse').then(({ useBrowseStore }) => useBrowseStore().reset()).catch(() => {});
  
  console.log('✅ 所有Pinia store已重置！');
}
